package ddns

import (
	"errors"
	"gitee.com/yysf-xin/dproxy/pkg/corn"
	"gitee.com/yysf-xin/dproxy/pkg/ddns/ip"
	"gitee.com/yysf-xin/dproxy/pkg/model"
	"gitee.com/yysf-xin/dproxy/pkg/tools"
	"github.com/robfig/cron/v3"
	"gopkg.in/yaml.v3"
	"net"
)

type Config struct {
	AccessKey    string `yaml:"access_key"`
	AccessSecret string `yaml:"access_secret"`

	Domain string `yaml:"domain"`
	Type   string `yaml:"type"`
	Url    string `yaml:"url"`
}
type Refresher interface {
	RefreshIP(domain string, ip net.IP) error
}

type service struct {
	Refresher
	cfg *Config
	p   ip.Provider
	tmp ip.Addr
}

func (s *service) refresh(oldIp net.IP, newIp net.IP) {
	if newIp != nil && !newIp.Equal(oldIp) {
		tools.Log.Println("refresh", s.cfg.Domain, newIp)
		err := s.RefreshIP(s.cfg.Domain, newIp)
		if err != nil {
			tools.Log.Println("refresh ip err", newIp.String(), err)
		} else {
			if len(newIp) == net.IPv4len {
				s.tmp.Ip4 = newIp
			} else {
				s.tmp.Ip6 = newIp
			}
		}
	}
}
func (s *service) Run() {
	addr := s.p.ObtainIp()
	if addr == nil {
		return
	}
	s.refresh(s.tmp.Ip4, addr.Ip4)
	s.refresh(s.tmp.Ip6, addr.Ip6)
}
func init() {
	corn.RegJob(corn.AliyunDDNS, "DDNS任务", func(ctl *corn.Control, cfg *model.CornConfig) (j cron.Job, err error) {
		key := new(Config)
		err = yaml.Unmarshal([]byte(cfg.Param), key)
		if err != nil {
			return
		}
		if key.AccessKey == "" || key.AccessSecret == "" || key.Domain == "" {
			err = errors.New("params err")
			return
		}
		s := &service{cfg: key}
		if key.Url == "" {
			s.p = &ip.Local{}
		} else {
			s.p = &ip.Remote{Url: key.Url}
		}
		if key.Type == "aliyun" {
			s.Refresher, err = NewAliYun(key)
		} else {
			err = errors.New("unknown err")
			return
		}
		j = s
		return
	})
}
